package com.xs.letcode;

/**
 * @author xs
 * date 2018/9/14 17:46
 * 给定两个非空链表来表示两个非负整数。位数按照逆序方式存储，它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
 * 你可以假设除了数字 0 之外，这两个数字都不会以零开头。
 * 输入：(2 -> 4 -> 3) + (5 -> 6 -> 4)
 * 输出：7 -> 0 -> 8
 * 原因：342 + 465 = 807
 */
public class TwoNumAdd {

    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode resultListNode = null;
        //上一个节点（始终指向上一个节点）
        ListNode lastNode = null;
        //是否进位
        int carry = 0;
        for (; (l1 != null || l2 != null) || carry ==1; ){
            int a = 0, b = 0;
            if (l1 != null) {
                a = l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                b = l2.val;
                l2 = l2.next;
            }
            int sum = a + b + carry;
            int current;
            if (sum >= 10) {
                carry = 1;
                current = sum - 10;
            } else {
                carry = 0;
                current = sum;
            }
            if (resultListNode == null) {
                resultListNode = new ListNode(current);
                lastNode = resultListNode;
            } else {
                //新的一个节点
                ListNode listNode = new ListNode(current);
                //连接前后两个节点
                lastNode.next = listNode;
                //指向新加入的节点
                lastNode = listNode;
            }
        }
        return resultListNode;
    }

    public static void main(String[] args) {
        //(2 -> 4 -> 3)
        ListNode node2 = new ListNode(2);
        ListNode node4 = new ListNode(4);
        ListNode node3 = new ListNode(3);

        node2.next = node4;
        node4.next = node3;

        //(5 -> 6 -> 4)
        ListNode nd5 = new ListNode(5);
        ListNode nd6 = new ListNode(6);
        ListNode nd4 = new ListNode(4);

        nd5.next = nd6;
        nd6.next = nd4;

//		ListNode listNode = addTwoNumbers(node2, nd5);
        ListNode listNode = addTwoNumbers(new ListNode(5), new ListNode(5));
        for (; listNode != null; ) {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }

    }


}
